﻿using System;
using System.ComponentModel;
using System.Linq;

namespace Fly.Common.Extensions
{
    /// <summary>
    /// 枚举类型扩展
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取指定枚举指定名的描述特性
        /// </summary>
        /// <param name="obj">枚举</param>
        /// <param name="index">多个描述时获取的描述索引</param>
        /// <returns></returns>
        public static string GetDescription(this Enum obj, int index = 0)
        {
            Type enumType = obj.GetType();
            var fields = enumType.GetFields().FirstOrDefault(row => row.Name.Equals(obj.ToString(), StringComparison.OrdinalIgnoreCase));
            if (fields != null)
            {
                var desArray = fields.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (desArray.Length >= index)
                {
                    DescriptionAttribute des = desArray[index] as DescriptionAttribute;
                    if (des != null)
                    {
                        return des.Description;
                    }
                }
            }
            return string.Empty;
        }
    }
}
